<?php

namespace app\api\service;

use app\api\model\AdminModel;
use app\api\model\AgentBranchModel;
use app\api\model\AgentCompanyModel;
use app\api\model\AgentModel;
use app\api\model\CompanyModel;
use app\api\model\ProductModel;
use think\Db;
use think\Exception;
use think\Request;
use think\Validate;

class AgentService extends Api
{
    protected static $instance;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }

    public static function getInstance()
    {
        if (is_null(self::$instance))
        {
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * 添加、编辑 经代/保司 披露信息
     */
    public function changeAgent($params)
    {
        $Validate = new Validate([
            'title' => 'require',
            'capital' => 'require',
            'establishment' => 'require',
            'legal_person' => 'require',
            'credit_code' => 'require',
            'company_address' => 'require',
            'business_nature' => 'require',
            'business_license' => 'require',
            'business_permit' => 'require',
            'agent_img' => 'require',
            'agent_domain' => 'require',
            'policy_verification_method' => 'require',
            'customer_service' => 'require',
            'status' => 'require',
            'phone' => 'require',
            'deduction' => 'require',
        ], [
            'title' => '经代/保司名称必填',
            'capital' => '注册资本必填',
            'establishment' => '成立时间必填',
            'legal_person' => '法人代表必填',
            'credit_code' => '信用编码必填',
            'company_address' => '经代/保司地址必填',
            'business_nature' => '经营范围必填',
            'business_license' => '营业执照必填',
            'business_permit' => '业务许可证必填',
            'agent_img' => '经代/保司图片必传',
            'agent_domain' => '经代/保司域名必填',
            'policy_verification_method' => '保单验证方式必填',
            'customer_service' => '客户服务及投诉渠道必填',
            'status' => '状态不可为空',
            'phone' => '联系方式必填',
            'deduction' => '扣费比例必填',
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }

        Db::startTrans();
        try{
            $saveData = [
                'title' => $params['title'],//'公司名称',
                'capital' => $params['capital'],//'注册资本',
                'establishment' => $params['establishment'],//'成立时间',
                'legal_person' => $params['legal_person'],//'法人代表',
                'credit_code' => $params['credit_code'],//'信用编码',
                'company_address' => $params['company_address'],//'公司地址',
                'business_nature' => $params['business_nature'],//'经营范围',
                'business_license' => json_encode($params['business_license']),//'营业执照',
                'business_permit' => json_encode($params['business_permit']),//'业务许可证',
                'agent_img' => json_encode($params['agent_img']),//'经代公司图片',
                'agent_domain' => $params['agent_domain'],//'经代公司域名',
                'policy_verification_method' => $params['policy_verification_method'],//'保单验证方式',
                'customer_service' => $params['customer_service'],//'客户服务及投诉渠道',
                'status' => $params['status'],//'信息状态： 0 不发布  1 发布  2 整理中',
                'phone' => $params['phone'],//'联系方式',
                'deduction' => $params['deduction'],
            ];
//            unset($params['policy_verification_method']);
//            unset($params['customer_service']);
            LogService::getInstance()->writeSysLog([
                'operation' => '/api/agent/changeAgent',
                'title' => !empty($params['id']) ? '编辑' : '添加',
                'content' => $params,
            ]);
            if (!empty($params['id']))
            {
                $saveData['u_time'] = datetime(time(), 'Y-m-d H:i:s');
                $res = AgentModel::getInstance()->update($params['id'], $saveData);
            }else{
                $saveData['admin_id'] = $this->uid;
                $saveData['c_time'] = datetime(time(), 'Y-m-d H:i:s');
                $res = AgentModel::getInstance()->insert($saveData);
            }

            Db::commit();
            return $res;
        }catch (Exception $e)
        {
            Db::rollback();
            $this->error('数据错误 请联系系统管理员操作');
//            $this->error($e->getMessage());
        }
    }

    /**
     * 获取保司披露信息列表
     */
    public function getAgentList($params)
    {
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 15);
        $start = ($page - 1) * $limit;

        $where = [];

        if ($this->uid > 1)
        {
            $adminIds[] = $this->uid;
            $thisAdminIds = array_column(AdminService::getInstance()->getAdmin([], true), 'id');
            $adminIds = array_merge($adminIds, $thisAdminIds);
            $teamIds = AdminModel::getInstance()->value([
                'id' => ['eq', $this->uid]
            ], 'team');
            $teamAdminIds = AdminModel::getInstance()->column([
                'team' => ['eq', $teamIds]
            ], 'id');
            $adminIds = array_unique(array_merge($adminIds, $teamAdminIds));
            $where['admin_id'] = ['in', $adminIds];
        }

        if (!empty($params['title']))
        {
            $where['title'] = ['LIKE', '%'.$params['title'].'%'];
        }
        if (!empty($params['legal_person']))
        {
            $where['legal_person'] = ['LIKE', '%'.$params['legal_person'].'%'];
        }
        if (isset($params['status']))
        {
            $where['status'] = ['eq', $params['status']];
        }

        $total = AgentModel::getInstance()->count($where);
        $list  = AgentModel::getInstance()->select($where, '*', $start, $limit);

        return [
            'total' => $total,
            'list' => $list
        ];
    }

    /**
     * 获取指定保司披露信息
     */
    public function getAgentInfo($params)
    {
        $Validate = new Validate([
            'id' => 'require',
        ], [
            'id' => '缺少披露信息记录id'
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        $info = AgentModel::getInstance()->find($params['id']);
        $info['business_license'] = json_decode($info['business_license'], true);
        $info['business_permit'] = json_decode($info['business_permit'], true);
        $info['agent_img'] = json_decode($info['agent_img'], true);
        return $info;
    }

    /**
     * 添加、编辑披露信息分支机构
     */
    public function changeAgentBranch($params)
    {
        $Validate = new Validate([
            'agent_id' => 'require',
            'branch' => 'require',
//            'title' => 'require',
//            'domain' => 'require'
        ], [
            'agent_id' => '缺少披露信息记录唯一标识',
            'branch' => '缺少分支机构数据'
//            'title' => '分支机构名称必填',
//            'domain' => '分支机构查询域名必填'
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }

        Db::startTrans();
        try{
            AgentBranchModel::getInstance()->delete([
                'agent_id' => ['eq', $params['agent_id']]
            ]);
            foreach ($params['branch'] as $k => $v)
            {
                $saveData = [
                    'agent_id' => $params['agent_id'],//int(10) DEFAULT NULL,
                    'title' => $v['title'],//varchar(128) DEFAULT NULL COMMENT '分支机构名称',
                    'domain' => $v['domain'],//varchar(128) DEFAULT NULL COMMENT '分支机构查询域名',
                ];
                if (!empty($params['id']))
                {
                    $saveData['u_time'] = datetime(time(), 'Y-m-d H:i:s');
                    $res = AgentBranchModel::getInstance()->update($params['id'], $saveData);
                }else{
                    $saveData['c_time'] = datetime(time(), 'Y-m-d H:i:s');
                    $res = AgentBranchModel::getInstance()->insert($saveData);
                }
            }

            LogService::getInstance()->writeSysLog([
                'operation' => '/api/agent/changeAgentBranch',
                'title' => !empty($params['id']) ? '编辑' : '添加',
                'content' => $params,
            ]);

            Db::commit();
            return $res;
        }catch (Exception $e)
        {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 获取信息披露分支机构信息
     */
    public function getAgentBranch($params)
    {
        $Validate = new Validate([
            'agent_id' => 'require'
        ], [
            'agent_id' => '缺少披露信息记录唯一标识'
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        $list = AgentBranchModel::getInstance()->select([
            'agent_id' => ['eq', $params['agent_id']]
        ], 'title,domain', 0, 100000);
        return $list;
    }

    /**
     * 添加、编辑披露信息合作记录信息
     */
    public function changeAgentCompany($params)
    {
        $Validate = new Validate([
            'agent_id' => 'require',
            'company' => 'require',
        ], [
            'agent_id' => '缺少披露信息记录唯一标识',
            'company' => '缺少合作记录信息',
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        $Validate = new Validate([
            'pro_id' => 'require',
            'title' => 'require',
            'cooperation_start_time' => 'require',
            'cooperation_end_time' => 'require',
            'insurance_company' => 'require',
            'record_num' => 'require',
            'insurance_clauses' => 'require',
        ], [
            'pro_id' => '缺少合作产品信息',
            'title' => '缺少备案名称',
            'cooperation_start_time' => '缺少合作开始时间',
            'cooperation_end_time' => '缺少合作结束时间',
            'insurance_company' => '缺少承包公司信息',
            'record_num' => '缺少备案文号',
            'insurance_clauses' => '缺少保险条款',
        ]);
        if ($Validate->check($params['company']))
        {
            $this->error($Validate->getError());
        }
        Db::startTrans();
        try{
            AgentCompanyModel::getInstance()->delete([
                'agent_id' => ['eq', $params['agent_id']]
            ]);
            foreach ($params['company'] as $k => $v)
            {
                $saveData[] = [
                    'agent_id' => $params['agent_id'],
                    'pro_id' => $v['pro_id'],
                    'title' => $v['title'],
                    'cooperation_start_time' => $v['cooperation_start_time'],
                    'cooperation_end_time' => $v['cooperation_end_time'],
                    'insurance_company' => $v['insurance_company'],
                    'record_num' => $v['record_num'],
                    'insurance_clauses' => json_encode($v['insurance_clauses']),
                    'c_time' => datetime(time(), 'Y-m-d H:i:s'),
                ];
            }

            LogService::getInstance()->writeSysLog([
                'operation' => '/api/agent/changeAgentCompany',
                'title' => !empty($params['id']) ? '编辑' : '添加',
                'content' => $params,
            ]);

            $res = AgentCompanyModel::getInstance()->insertAll($saveData);
            Db::commit();
            return $res;
        }catch (Exception $e)
        {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 获取披露信息合作记录
     */
    public function getAgentCompany($params)
    {
        $Validate = new Validate([
            'agent_id' => 'require',
        ], [
            'agent_id' => '缺少披露信息记录唯一标识'
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        $list = AgentCompanyModel::getInstance()->select([
            'agent_id' => ['eq', $params['agent_id']]
        ]);
        $proName = ProductModel::getInstance()->column([], 'product_name');

        $companyName = CompanyModel::getInstance()->column([], 'name');
        foreach ($list as $k => $v)
        {
            $list[$k]['cooperation_start_time'] = $this->stampToDate(strtotime($v['cooperation_start_time']), 'Y-m-d');
            $list[$k]['cooperation_end_time'] = $this->stampToDate(strtotime($v['cooperation_end_time']), 'Y-m-d');
            $list[$k]['insurance_clauses'] = json_decode($v['insurance_clauses'], true);
            $tProName = '';
            foreach (explode(',', $v['pro_id']) as $kk => $vv)
            {
                $tProName .= isset($proName[$vv]) ? (empty($tProName) ? $proName[$vv] : '、 '.$proName[$vv]) : '';
            }
            $list[$k]['companyName'] = $companyName[$v['insurance_company']];
            $list[$k]['proName'] = $tProName;
        }
        return $list;
    }

    /**
     * 获取经代公司 - 下拉框使用
     */
    public function getAgentCompanyList($params)
    {
        $list = AgentModel::getInstance()->select([
            'status' => ['eq', 1]
        ], 'id, title');
        return $list;
    }
}